import Clipboard from 'clipboard'
import CryptoJS from 'crypto-js'

//加密
export const encrypt = (word, keyStr) =>{
  keyStr = keyStr ? keyStr : 'abcdefgabcdefg12';
  var key  = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  return encrypted.toString();
};
//解密
export const decrypt = (word, keyStr) => {
  keyStr = keyStr ? keyStr : 'abcdefgabcdefg12';
  var key  = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
};

export const forEach = (arr, fn) => {
  if (!arr.length || !fn) return
  let i = -1
  let len = arr.length
  while (++i < len) {
    let item = arr[i]
    fn(item, i, arr)
  }
}

//得到两个数组的交集, 两个数组的元素为数值或字符串
export const getIntersection = (arr1, arr2) => {
  let len = Math.min(arr1.length, arr2.length)
  let i = -1
  let res = []
  while (++i < len) {
    const item = arr2[i]
    if (arr1.indexOf(item) > -1) res.push(item)
  }
  return res
}

//得到两个数组的并集, 两个数组的元素为数值或字符串
export const getUnion = (arr1, arr2) => {
  return Array.from(new Set([...arr1, ...arr2]))
}

/**
 * @param {Array} target 目标数组
 * @param {Array} arr 需要查询的数组
 * @description 判断要查询的数组是否至少有一个元素包含在目标数组中
 */
export const hasOneOf = (targetarr, arr) => {
  return targetarr.some(_ => arr.indexOf(_) > -1)
}

/**
 * @param {String|Number} value 要验证的字符串或数值
 * @param {*} validList 用来验证的列表
 */
export function oneOf (value, validList) {
  for (let i = 0; i < validList.length; i++) {
    if (value === validList[i]) {
      return true
    }
  }
  return false
}

/**
 * @param {Number} timeStamp 判断时间戳格式是否是毫秒
 * @returns {Boolean}
 */
const isMillisecond = timeStamp => {
  const timeStr = String(timeStamp)
  return timeStr.length > 10
}

/**
 * @param {Number} timeStamp 传入的时间戳
 * @param {Number} currentTime 当前时间时间戳
 * @returns {Boolean} 传入的时间戳是否早于当前时间戳
 */
const isEarly = (timeStamp, currentTime) => {
  return timeStamp < currentTime
}

/**
 * @param {Number} num 数值
 * @returns {String} 处理后的字符串
 * @description 如果传入的数值小于10，即位数只有1位，则在前面补充0
 */
const getHandledValue = num => {
    return num < 10 ? '0' + num : num
}

//判断根据十进制值判断颜色深浅并选择反差色
export const getBgColor = number => {
    return number > 15607077 ? "#000000" : "#ffffff";
}
//十进制颜色值 转换 成16进制颜色码
export const getColor = value => {
    let bgcolor = Number(value).toString(16);
    bgcolor = bgcolor.length >= 6 ? bgcolor : bgcolor.padStart(6, "0");
    return "#"+bgcolor;
}
//颜色码#E13838 转换 成十进制14759992
export const setColor = hexColor => {
    // 去除#号
    const hex = hexColor.replace('#', '');
    // 将十六进制转为十进制整数
    return parseInt(hex, 16);
}
//小数截取1.2394  =>  1.23
export const numberSubstr = (num, decimalPlaces) => {
    num = num.toString();
    let numArr = num.split('.');
    let outNum = 0;
    if(numArr.length == 1 || numArr[1].length <=2){
        outNum = parseFloat(num);
    }else{
        outNum = parseFloat(numArr[0]+"."+numArr[1].substr(0, decimalPlaces));
    }
    //console.log("小数截取", num, outNum);
    return outNum;
}

//自定义尺码排序
export const sizeSort = sizes => {
    // 自定义排序函数
    sizes.sort((a, b) => {
        // 定义标准尺码顺序
        const sizeMap = { 'XXS': 0, 'XS': 1, 'S': 2, 'M': 3, 'L': 4, 'XL': 5, 'XXL': 6, 'XXXL': 7, 'Y': 8, 'B': 9 };

        // 判断是否为数字尺码
        const isANumeric = !isNaN(parseFloat(a)) && isFinite(a);
        const isBNumeric = !isNaN(parseFloat(b)) && isFinite(b);

        // 数字与数字比较
        if (isANumeric && isBNumeric) {
            return parseFloat(a) - parseFloat(b);
        }

        // 字母与字母比较
        if (!isANumeric && !isBNumeric) {
            return (sizeMap[a] || 0) - (sizeMap[b] || 0);
        }

        // 数字与字母比较：数字永远排在前面
        return isANumeric ? -1 : 1;
    });
    return sizes;
}

/**
 * @param {Number} timeStamp 传入的时间戳
 * @param {Number} startType 要返回的时间字符串的格式类型，传入'year'则返回年开头的完整时间
 * 在JavaScript中，使用new Date()构造函数创建日期对象时，月份参数是从0开始的，即0代表1月，1代表2月，以此类推，直到11代表12月
 */
export const formatDate = (timeStamp, startType) => {
    const d = new Date(parseInt(timeStamp));
    let year = d.getFullYear();
    let month = getHandledValue(d.getMonth() + 1);
    let last_month = getHandledValue(d.getMonth());
    let date = getHandledValue(d.getDate())
    let hours = getHandledValue(d.getHours());
    let minutes = getHandledValue(d.getMinutes());
    let second = getHandledValue(d.getSeconds());
    switch (startType) {
        case "datetime":
            return year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + second;
        case "date":
            return year + '-' + month + '-' + date;
        case "year":
            return year.toString();
        case "last_year":
            return (year-1).toString();
        case "month":
            return year + '-' + month;
        case "month_first_day":
            return year + '-' + month + '-01';
        case "month_last_day":
            return year + '-' + month + '-' + (new Date(year, month, 0).getDate());
        case "last_month":
            if(last_month == "00"){
                last_month = "12";
                year = year-1;
            }
            return year + '-' + last_month;
        case "last_month_first_day":
            return year + '-' + last_month + '-01';
        case "last_month_last_day":
            return year + '-' + last_month + '-' + (new Date(year, last_month, 0).getDate());
        default:
            return year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + second;
    }
}

/**
 * @param {String|Number} timeStamp 时间戳
 * @returns {String} 相对时间字符串
 */
export const getRelativeTime = timeStamp => {
  // 判断当前传入的时间戳是秒格式还是毫秒
  const IS_MILLISECOND = isMillisecond(timeStamp)
  // 如果是毫秒格式则转为秒格式
  if (IS_MILLISECOND) Math.floor(timeStamp /= 1000)
  // 传入的时间戳可以是数值或字符串类型，这里统一转为数值类型
  timeStamp = Number(timeStamp)
  // 获取当前时间时间戳
  const currentTime = Math.floor(Date.parse(new Date()) / 1000)
  // 判断传入时间戳是否早于当前时间戳
  const IS_EARLY = isEarly(timeStamp, currentTime)
  // 获取两个时间戳差值
  let diff = currentTime - timeStamp
  // 如果IS_EARLY为false则差值取反
  if (!IS_EARLY) diff = -diff
  let resStr = ''
  const dirStr = IS_EARLY ? '前' : '后'
  // 少于等于59秒
  if (diff <= 59) resStr = diff + '秒' + dirStr
  // 多于59秒，少于等于59分钟59秒
  else if (diff > 59 && diff <= 3599) resStr = Math.floor(diff / 60) + '分钟' + dirStr
  // 多于59分钟59秒，少于等于23小时59分钟59秒
  else if (diff > 3599 && diff <= 86399) resStr = Math.floor(diff / 3600) + '小时' + dirStr
  // 多于23小时59分钟59秒，少于等于29天59分钟59秒
  else if (diff > 86399 && diff <= 2623859) resStr = Math.floor(diff / 86400) + '天' + dirStr
  // 多于29天59分钟59秒，少于364天23小时59分钟59秒，且传入的时间戳早于当前
  else if (diff > 2623859 && diff <= 31567859 && IS_EARLY) resStr = getDate(timeStamp)
  else resStr = getDate(timeStamp, 'year')
  return resStr
}

/**
 * @returns {String} 当前浏览器名称
 */
export const getExplorer = () => {
  const ua = window.navigator.userAgent
  const isExplorer = (exp) => {
    return ua.indexOf(exp) > -1
  }
  if (isExplorer('MSIE')) return 'IE'
  else if (isExplorer('Firefox')) return 'Firefox'
  else if (isExplorer('Chrome')) return 'Chrome'
  else if (isExplorer('Opera')) return 'Opera'
  else if (isExplorer('Safari')) return 'Safari'
}

/**
 * @description 绑定事件 on(element, event, handler)
 */
export const on = (function () {
  if (document.addEventListener) {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.addEventListener(event, handler, false)
      }
    }
  } else {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.attachEvent('on' + event, handler)
      }
    }
  }
})()

/**
 * @description 解绑事件 off(element, event, handler)
 */
export const off = (function () {
  if (document.removeEventListener) {
    return function (element, event, handler) {
      if (element && event) {
        element.removeEventListener(event, handler, false)
      }
    }
  } else {
    return function (element, event, handler) {
      if (element && event) {
        element.detachEvent('on' + event, handler)
      }
    }
  }
})()

/**
 * 判断一个对象是否存在key，如果传入第二个参数key，则是判断这个obj对象是否存在key这个属性
 * 如果没有传入key这个参数，则判断obj对象是否有键值对
 */
export const hasKey = (obj, key) => {
  if (key) return key in obj
  else {
    let keysArr = Object.keys(obj)
    return keysArr.length
  }
}

/**
 * @param {*} obj1 对象
 * @param {*} obj2 对象
 * @description 判断两个对象是否相等，这两个对象的值只能是数字或字符串
 */
export const objEqual = (obj1, obj2) => {
    const keysArr1 = Object.keys(obj1)
    const keysArr2 = Object.keys(obj2)
    if (keysArr1.length !== keysArr2.length) return false
    else if (keysArr1.length === 0 && keysArr2.length === 0) return true
    /* eslint-disable-next-line */
    else return !keysArr1.some(key => obj1[key] != obj2[key])
}

/**
 * 文字内容 复制
 * <mt-button class="copyTag" @click="copyBtn(content)">复制</mt-button>
 * copyText(".clickTag", content);
 */
export function copyText(copyTag, content) {
    let clipboard = new Clipboard(copyTag,{
        text: () => {
            return content;
        }
    });
    clipboard.on("success", () => {
        clipboard.destroy();
    });
    clipboard.on("error", () => {
        clipboard.destroy();
    });
};

/**
 * 图片文字 复制
 * <el-popover placement="top-start" width="400" trigger="hover">
 *     <div id="copyContent">
 *         <img src=""/>
 *         <div v-html="content"></div>
 *     </div>
 *     <el-button type="primary" slot="reference" id="clickTag" @click="copyBtn" :disabled="!copyContentDom">复制</el-button>
 * </el-popover>
 *
 * copy("#copyBtn", "#copyContent");
 */
export function copy(copyBtn, copyContent) {
    var clipboard=new Clipboard(copyBtn,{
        target:function(){
            return document.querySelector(copyContent)
        }
    });
    clipboard.on('success', function(e) {
        clipboard.destroy();// 复制完毕删除，否则会有创建多个clipboard对象
    });
    clipboard.on('error', function(e) {
        console.log(e);
        clipboard.destroy()
    });
};

export function downloadImg(url, name){
    let image = new Image();
    // 解决跨域 canvas污染问题
    image.setAttribute('crossOrigin', 'anonymous')
    image.src = url + '?time=' + new Date().valueOf() // 加时间戳
    this.$nextTick(() => {
        image.onload = () => {
            const canvas = document.createElement('canvas')
            canvas.width = image.width
            canvas.height = image.height
            const context = canvas.getContext('2d')
            context.drawImage(image, 0, 0, image.width, image.height)
            canvas.toBlob((blob) => {
                const url = URL.createObjectURL(blob)
                const a = document.createElement('a')
                a.download = name
                a.href = url
                a.click()
                a.remove()
                URL.revokeObjectURL(url)
            })
        }
    })
}
